/*================================================================
 *   Copyright (C) 2021 www.hsby.link All rights reserved.
 *   
 *   文件名称：test_iomanager.cc
 *   创 建 者：汉森伯逸
 *   创建日期：2021/5/3
 *   描    述：
 *
 *================================================================*/
#include <arpa/inet.h>
#include "hsby.h"

int sock;

void task_cb() {
    //HSBY_LOG_SYSTEM_DEBUG << "begin task_cb()";
    //HSBY_LOG_SYSTEM_DEBUG << "end task_cb()";
}

void test_socket_cb() {
    //HSBY_LOG_SYSTEM_DEBUG << "begin test_socket()";

    sock = socket(AF_INET, SOCK_STREAM, 0);
    fcntl(sock, F_SETFL, O_NONBLOCK);
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    memset(&addr, 0, len);

    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);
    inet_pton(AF_INET, "220.181.38.148", &addr.sin_addr.s_addr);

    // 非阻塞connect时连接成功返回-1且设置errno=EINPROGRESS
    if(connect(sock, (const sockaddr*)&addr, sizeof(addr)) && errno == EINPROGRESS) {
        //HSBY_LOG_SYSTEM_DEBUG << "add event errno=" << errno << " " << strerror(errno);
        hsby::IoManager::GetCurrentIoManager()->SetEvent(sock, EPOLLIN, []() {
            //HSBY_LOG_SYSTEM_DEBUG << "read callback";
        });
        hsby::IoManager::GetCurrentIoManager()->SetEvent(sock, EPOLLOUT, []() {
            //HSBY_LOG_SYSTEM_DEBUG << "write callback";

            hsby::IoManager::GetCurrentIoManager()->TriggerEvent(sock, EPOLLIN);
            close(sock);
        });
    } else {
        //HSBY_LOG_SYSTEM_DEBUG << "else " << errno << " " << strerror(errno);
    }

    //HSBY_LOG_SYSTEM_DEBUG << "end test_socket()";
}

void test_iomanager() {
    hsby::IoManager iom(1, "test");
    iom.AddTask(&test_socket_cb);
}

void test_timer() {
    hsby::IoManager iom(1, "test");
    hsby::Timer::Ptr timer1 = iom.AddTimer(500, [&timer1]() {
        static int i = 0;
        if (++i == 3) {
            timer1->Reset(2000);
        }
        HSBY_LOG_SYSTEM_INFO << "timer1 massage per 1000ms i=" << i;
    }, true) ;
}

void test_tack() {
    HSBY_LOG_SYSTEM_DEBUG << "in test_stack";
}

int main() {
    hsby::IoManager iom(1, "test");
    iom.AddTask(test_tack);
    iom.AddTask(test_tack);
    iom.AddTask(test_tack);
    iom.AddTask(test_tack);
    return 0;
}